<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="850px">
    <el-form :model="formData" ref="formRef" :rules="formRules" vloading="formLoading">
      <el-row>
        <el-col :span="12">
          <el-form-item label="姓名" prop="elderName">
            <el-input v-model="formData.elderName" disabled class="mr-1" />
            <el-button @click="clickChooseElder">选择老人</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用药时间" prop="useTime">
            <el-date-picker
              v-model="formData.useTime"
              placeholder="请输入用药时间"
              value-format="YYYY-MM-DD HH:mm:ss"
              :clearable="true"
              type="datetime"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-form-item>
      <el-button @click="clickAddMedicine">添加药品</el-button>
      <el-button @click="clickDeleteMedicine">删除药品</el-button>
    </el-form-item>
    <Table
      :columns="columns"
      :adaptive="true"
      :data="formData.details"
      save-key="HealthMedicineRegisterTemporary"
      @row-click="handleRowClick"
    >
      <template #medicineType="{ row }">
        {{ getDictObj(DICT_TYPE.HEALTH_MEDICINE_TYPE, row.medicine.medicineType).label }}
      </template>
      <template #medicineDosageForm="{ row }">
        {{
          getDictObj(DICT_TYPE.HEALTH_MEDICINE_DOSAGE_FORM, row.medicine.medicineDosageForm).label
        }}
      </template>
      <template #useNumber="{ row }">
        <InputNumber v-model="row.useNumber" class="!w-70px" type="decimal" />
      </template>
    </Table>

    <template #footer>
      <el-button type="primary" :disabled="formLoading" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
  <HealthMedicineSelect ref="healthMedicineSelectRef" @select-value="handleSelectHealthMedicine" />
  <ElderInfoSelect ref="elderInfoSelectRef" @row-dblclick="handleSelectElderInfo" />
</template>
<script setup name="HealthMedicineRegisterTemporary" lang="ts">
import { DICT_TYPE, getDictObj } from '@/utils/dict'
import HealthMedicineSelect from '@/views/health/healthMedicine/HealthMedicineSelect.vue'
import ElderInfoSelect from '@/views/elder/elderInfo/ElderInfoSelect.vue'
import * as HealthMedicineRegisterModel from '@/model/health/medicine/HealthMedicineRegister'
import * as HealthMedicineRegisterApi from '@/api/health/medicineRegister'
import InputNumber from '@/components/InputNumber/src/InputNumber.vue'
interface HealthMedicineRegisterTemporaryDetail
  extends HealthMedicineRegisterModel.HealthMedicineRegister {
  medicine: {
    medicineName: string
    medicineBrevityCode: string
    medicineSpecification: string
    medicineDosageForm: string
  }
}
interface HealthMedicineRegisterTemporary {
  elderId: number | undefined
  elderName: string
  useTime: string
  details: HealthMedicineRegisterTemporaryDetail[]
}
const { t } = useI18n()
const message = useMessage()
const dialogTitle = ref('')
const dialogVisible = ref(false)
const formRef = ref()
const formLoading = ref(false)
const formData = ref<HealthMedicineRegisterTemporary>({
  elderId: undefined,
  elderName: '',
  useTime: '',
  details: []
})
const healthMedicineSelectRef = ref()
const elderInfoSelectRef = ref()
const formRules = reactive({
  name: [{ required: true, message: '请输入姓名', trigger: 'change' }],
  useTime: [{ required: true, type: 'date', message: '请输入用药时间', trigger: 'change' }]
})
const tableCurrentRow = ref()
const columns = [
  {
    label: '药品名称',
    prop: 'medicine.medicineName'
  },
  {
    label: '药品简码',
    prop: 'medicine.medicineBrevityCode'
  },
  {
    label: '药品类型',
    prop: 'medicine.medicineType',
    slot: 'medicineType'
  },
  {
    label: '药品规格',
    prop: 'medicine.medicineSpecification'
  },
  {
    label: '药品剂型',
    prop: 'medicine.medicineDosageForm',
    slot: 'medicineDosageForm'
  },
  {
    label: '用药数量',
    prop: 'useNumber',
    slot: 'useNumber'
  }
]
/** 打开弹窗 */
const open = () => {
  dialogVisible.value = true
  resetForm()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    elderId: undefined,
    elderName: '',
    useTime: '',
    details: []
  }
  formRef.value?.resetFields()
}

const emit = defineEmits(['success'])
/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  if (formData.value.details.length <= 0) {
    message.alert('请选择药品')
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value
      .details as unknown as HealthMedicineRegisterModel.HealthMedicineRegister[]
    data.forEach((detail) => {
      detail.elderId = formData.value.elderId
      detail.useTime = formData.value.useTime
    })
    await HealthMedicineRegisterApi.temporaryCreate(data)
    message.success(t('common.createSuccess'))
    dialogVisible.value = false
  } finally {
    formLoading.value = false
  }
  emit('success')
}

/** table行点击事件 */
const handleRowClick = (row) => {
  tableCurrentRow.value = row
}

/** 单击新增药品 */
const clickAddMedicine = () => {
  healthMedicineSelectRef.value.open()
}

const clickChooseElder = () => {
  elderInfoSelectRef.value.open()
}

const handleSelectHealthMedicine = (selectMaterialStockList) => {
  selectMaterialStockList.forEach((element) => {
    const detail = {
      id: undefined,
      medicineId: element.id,
      elderId: undefined,
      useNumber: 1,
      useTime: '',
      useType: 2,
      medicine: {
        medicineName: element.medicineName,
        medicineBrevityCode: element.medicineBrevityCode,
        medicineType: element.medicineType,
        medicineSpecification: element.medicineSpecification,
        medicineDosageForm: element.medicineDosageForm
      }
    }
    formData.value.details.push(detail)
  })
}

const handleSelectElderInfo = (selectElderInfo) => {
  formData.value.elderName = selectElderInfo.name
  formData.value.elderId = selectElderInfo.id
}

/** 单击删除药品 */
const clickDeleteMedicine = () => {
  if (tableCurrentRow.value === undefined) {
    message.alertError('请选择要删除的药品')
    return
  }

  const index = formData.value.details.indexOf(tableCurrentRow.value)
  formData.value.details.splice(index, 1)
}
</script>
